<template>
  <!-- 组织结构管理 -->
  <div class="module_" ref="module">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="一级科室" name="first"></el-tab-pane>
      <el-tab-pane label="二级科室" name="second"></el-tab-pane>
    </el-tabs>
    <div v-if="activeName == 'first'" class="flex-space-between mb8 search_box">
      <el-form :inline="true"  class="user-search">
        <el-form-item label="搜索：">
          <el-input
            size="small"
            v-model.trim="firstParmas.name"
            placeholder="输入科室名称搜索"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="firstSearch"
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="clearSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <el-button
        class="mr8"
        size="small"
        type="primary"
        @click="firstHandle(null, {}, 3)"
        >添加一级科室</el-button
      >
    </div>
    <div v-else class="flex-space-between mb8 search_box subSearch">
      <el-form :inline="true">
        <el-form-item label="搜索：">
          <el-select v-model="secondParmas.department_id" clearable filterable placeholder="一级科室搜索" style="height:32px" @change="onChange('department_id')">
            <el-option
              v-for="item in cacheDepartments"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="secondParmas.name" clearable filterable placeholder="二级科室名称搜索" style="height:32px" @change="onChange('name')">
            <el-option
              v-for="item in cacheSubDepartments"
              :key="item.id"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="secondParmas.code" clearable filterable placeholder="科室号搜索" style="height:32px" @change="onChange('code')">
            <el-option
              v-for="item in cacheSubDepartments"
              :key="item.id"
              :label="item.code +':' + item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <br/>
        <el-form-item class="ml55">
          <el-select v-model="secondParmas.type_lv1" clearable placeholder="选择科室类型一搜索" style="height:32px" @change="onChange('type_lv1')">
            <el-option
              v-for="item in type_lv1"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="secondParmas.type_lv2" clearable placeholder="选择科室类型二搜索" style="height:32px" @change="onChange('type_lv2')">
            <el-option
              v-for="item in type_lv2"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="secondParmas.type_lv3" clearable placeholder="选择科室类型三搜索" style="height:32px" @change="onChange('type_lv3')">
            <el-option
              v-for="item in type_lv3"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            type="primary"
            icon="el-icon-search"
            @click="subSearch"
            >搜索</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="clearSubSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-show="activeName == 'first'" class="flex-1 flex-ver">
      <el-table
        ref="firstTable"
        :max-height="firstHeight"
        :height="firstHeight"
        :data="partmentsList"
        size="small"
        border
        highlight-current-row
        v-loading="tableLoading"
        stripe	
        @sort-change="firstSortChange">
        <el-table-column
          fixed
          align="center"
          prop="name"
          label="科室名称"
          width="200"
          show-overflow-tooltip
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="house_price"
          label="房屋使用单价"
          width="150"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="house_space"
          label="房屋面积"
          width="120"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="service_income_target_value"
          label="医疗服务收入目标值"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="device_maintain"
          label="设备维护费用"
          width="150"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="current_period_controllable_variable_cost"
          label="本期可控变动成本"
          width="150"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="base_department_income"
          label="基期科内有效收入"
          width="150"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="base_period_controllable_variable_cost"
          label="基期可控变动成本"
          width="150"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="variable_cost_control_deduction_rate"
          label="变动成本控制扣罚比率"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="is_performance"
          label="是否参与绩效"
          width="150"
          sortable="custom">
          <template slot-scope="props">
            {{props.row.is_performance ? '是' : '否'}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_average_cost"
          label="目标(基期)门诊均例费用"
          width="200"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_patient_count"
          label="科室基期门急诊人次"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_in_hospital_day"
          label="目标平均住院日"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_average_leave_cost"
          label="目标出院病人均例费用"
          width="200"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_average_drug_cost"
          label="目标出院病人均例药品费用"
          width="200"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_average_material_cost"
          label="目标出院病人均例耗材费用"
          width="200"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="base_use_bed_day"
          label="科室基期占床日"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_stay_bed_day"
          label="目标术前待床日"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="punish_amount"
          label="扣罚金额"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="reward_amount"
          label="奖励金额"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="point_price"
          label="点数单价"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_admission_rate"
          label="目标收治率"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="target_surgery_rate"
          label="目标手术率"
          width="180"
          sortable="custom">
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="150" fixed='right'>
          <template slot-scope="props">
            <el-tooltip  effect="dark" content="修改信息" placement="bottom-end">
              <el-button size="mini"  @click="firstHandle(props.$index, props.row, 2)" icon="el-icon-edit" circle></el-button>
            </el-tooltip>
            <el-tooltip  effect="dark" content="新增二级科室" placement="bottom-end">
              <el-button size="mini" type="primary" @click="handleSub(props.$index, props.row,1)" icon="el-icon-circle-plus" circle></el-button>
            </el-tooltip>
            <el-tooltip  effect="dark" content="删除" placement="bottom-end">
              <el-button size="mini" type="danger" @click="deleteUser(props.$index, props.row)" icon="el-icon-delete" circle></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <Pagination class="bg-white"  :child-msg="firstParmas" @callFather="firstcallFather" />
    </div>
    <div v-show="activeName != 'first'" class="flex-1 flex-ver">
      <el-table
        ref="SubTable"
        :data="subList"
        :height="secondHeight"
        :max-height="secondHeight"
        size="small"
        border
        highlight-current-row
        v-loading="tableLoading"
        stripe	
        @sort-change="secondSortChange">
        <el-table-column
          align="center"
          prop="department.name"
          label="一级科室名称"
          width="200"
          show-overflow-tooltip
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="name"
          label="二级科室名称"
          width="200"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="code"
          label="科室号"
          width="150"
          sortable="custom">
        </el-table-column>
        <el-table-column
          align="center"
          prop="type_lv1"
          label="科室类型一"
          width="180"
          sortable="custom">
          <template slot-scope="props">
            <p>{{ props.row.type_lv1 | type_lv1_filter  }}</p>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="type_lv2"
          label="科室类型二"
          width="180"
          sortable="custom">
          <template slot-scope="props">
            <p>{{ props.row.type_lv2 | type_lv2_filter  }}</p>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="type_lv3"
          label="科室类型三"
          width="180"
          sortable="custom">
          <template slot-scope="props">
            <p>{{ props.row.type_lv3 | type_lv3_filter  }}</p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="100">
          <template slot-scope="scope">
            <el-tooltip  effect="dark" content="修改信息" placement="bottom-end">
              <el-button size="mini"  @click="handleSub(scope.$index, scope.row, 2)" icon="el-icon-edit" circle></el-button>
            </el-tooltip>
            <el-tooltip  effect="dark" content="删除" placement="bottom-end">
              <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete" circle></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <Pagination class="bg-white" :child-msg="secondParmas" @callFather="secondcallFather" />

    </div>
    
    <partmentsDialo ref="partmentsDialo" :editForm="firstEditForm" :btnLoading='btnLoading' @submit='firstSubmit' />
    <subDialo ref="subDialo" :editForm='editFormSub' :btnLoading='btnLoading' @submit='SubSubmit' />
  </div>
</template>

<script>
import {Apidepartments,
        ApidepartmentsAdd,
        ApidepartmentsPut,
        ApidepartmentsDel,
        Apisub_departments,
        Apisub_departmentsAdd,
        Apisub_departmentsPut,
        Apisub_departmentsDel } from "@/api";
import { debounce } from "@/utils/index";
import partmentsDialo from "../components/partmentsDialo";
import subDialo from "../components/subDialo";
import {mapActions,mapState} from 'vuex'
import {type_lv1,type_lv2,type_lv3} from '@/assets/js'

export default {
  components: {
    partmentsDialo,
    subDialo,
  },
  computed:{
    ...mapState(['cacheDepartments','cacheSubDepartments'])
  },
  data() {
    return {
      firstHeight:null,
      secondHeight:null,
      partmentsList: [], //一级科室数据
      subList: [], //二级科室数据
      activeName: "first",
      firstEditForm: {}, //需要修改或者编辑的一级科室
      editFormSub: {},   //需要修改或者编辑的二级科室

      firstParmas: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: "updated_at",
        sort_order: "desc",
        name:null,
      },
      secondParmas: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: "updated_at",
        sort_order: "desc",
        department_id: null,
        name: null,
        code: null,
        type_lv1: null,
        type_lv2:	null,
        type_lv3: null,   
      },
      tableLoading: false,
      firstSearchObj: {},
      type_lv1,
      type_lv2,
      type_lv3,
      btnLoading:false,
    };
  },
  mounted() {
    this.getPartmentsList();
    let height = this.$refs.module.offsetHeight
    this.firstHeight = height-54-50-40-10
    this.secondHeight = height-54-90-40-10
  },
  methods: {
    ...mapActions(['getCacheDepartments','getCacheSubDepartments']),
    //tab切换
    handleClick: debounce(
      function () {
        this.firstParmas = {...this.firstParmas,name:null}
        this.secondParmas = {...this.secondParmas,department_id:null,name:null,code:null,type_lv1:null,type_lv2:null,type_lv3:null}
        if (this.activeName === "first") {
          this.getPartmentsList();
        } else {
          this.getSubList();
        }
      },
      300,
      false
    ),
    //二级科室操作
    onChange(val){
      // if(!this.secondParmas[val] && this.secondParmas[val] !== 0) this.secondParmas[val] = null
      this.secondParmas[val] = this.secondParmas[val] || null
      this.secondParmas.page = 1
      this.getSubList()
    },
    subSearch: debounce(function() {
      if(!this.secondParmas.name) this.secondParmas.name = null
      if(!this.secondParmas.code) this.secondParmas.code = null
      this.secondParmas.page = 1
      this.getSubList()
    },800,true),
    clearSubSearch: debounce(function(){
      this.secondParmas.page = 1
      this.secondParmas = {...this.secondParmas,department_id:null,name:null,code:null,type_lv1:null,type_lv2:null,type_lv3:null}
      this.getSubList()
    },800,true),
    getSubList(flag=false) {
      this.tableLoading = true;
      Apisub_departments(this.secondParmas)
        .then(({ data, page }) => {
          this.subList = data;
          this.secondParmas.total = page.total;
          this.tableLoading = false;
          this.$nextTick(() => {
            this.$refs.SubTable.doLayout()
            if(flag) this.getCacheSubDepartments()
          })
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    SubSubmit(value){   //二级科室的新增或者修改
      this.btnLoading = true
      if(value.id){
        Apisub_departmentsPut(value, value.id)
          .then((res) => {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.$refs.subDialo.show = false;
            this.getSubList(true);
          })
          .catch(() => {
            this.$message({
              type: "error",
              message: "修改失败!",
            });
          }).finally(()=>{
              this.btnLoading = false
            });
      }else{
        Apisub_departmentsAdd(value).then(res => {
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.$refs.subDialo.show = false;
          this.getSubList(true);
        }).catch(() => {
            this.$message({
              type: "error",
              message: "添加失败!",
            });
          }).finally(()=>{
            this.btnLoading = false
          });
      }
    },
    handleSub(index, value,i) {
      this.editFormSub = {}
      if(i == 1){
        this.editFormSub = { 
          parent_id: value.id,
          parent_name: value.name
        };
      }else if(i == 2){
        this.editFormSub = { 
          id: value.id,
          type_lv1: value.type_lv1,
          type_lv2: value.type_lv2,
          type_lv3: value.type_lv3,
          code: value.code,
          name: value.name,
          parent_id: value.department.id,
          parent_name: value.department.name
        };
      }
      this.$refs.subDialo.show = true;
    },
    secondcallFather(pageparm) {
      this.secondParmas.page = pageparm.page;
      this.secondParmas.perPage = pageparm.perPage;
      this.getSubList();
    },
    secondSortChange(column) {
      if (column.order === "descending") {
        this.secondParmas.sort_str = column.prop;
        this.secondParmas.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.secondParmas.sort_str = column.prop;
        this.secondParmas.sort_order = "asc";
      } else {
        this.secondParmas.sort_str = null;
        this.secondParmas.sort_order = null;
      }
      if (column.prop == "department.name")
        this.secondParmas.sort_str = "parent_id";
        this.getSubList();
    },
    //删除
    deleteUser(index,value) {
      let del = this.activeName === 'first'? ApidepartmentsDel : Apisub_departmentsDel
      let fun = this.activeName === 'first'? 'getPartmentsList' : 'getSubList'
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        const loading = this.$loading({
          lock: true,
          text: '加载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        del(value.id).then((res) => {
          this[fun](true);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        }).finally(()=>{
          loading.close()
        });
      })
      .catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
    },
    //一级科室操作
    firstSearch: debounce(function() {
      this.firstParmas.page = 1
      if(!this.firstParmas.name) this.firstParmas.name = null
      this.getPartmentsList()
    },800,true),
    clearSearch: debounce(function(){
      this.firstParmas.page = 1
      this.firstParmas.name = null
      this.getPartmentsList()
    },800,true),
    firstHandle(index, value,i) {
      this.firstEditForm = { ...value };
      this.$refs.partmentsDialo.show = true;
    },
    firstSubmit(value){
      this.btnLoading = true
      if(value.id){
        ApidepartmentsPut(value,value.id).then(res => {
          this.$message({
            type: "success",
            message: "修改成功!",
          });
          this.$refs.partmentsDialo.show = false;
          this.getPartmentsList(true);

        }).catch(() => {
            this.$message({
              type: "error",
              message: "修改失败!",
            });
          }).finally(()=>{
            this.btnLoading = false
          });
      }else{
        ApidepartmentsAdd(value).then(res => {
          this.$message({
            type: "success",
            message: "添加成功!",
          });
          this.$refs.partmentsDialo.show = false;
          this.getPartmentsList(true);
        }).catch(() => {
            this.$message({
              type: "error",
              message: "添加失败!",
            });
          }).finally(()=>{
            this.btnLoading = false
          });
      }
    },
    getPartmentsList(flag=false) {
      this.tableLoading = true;
      Apidepartments(this.firstParmas)
        .then(({ data, page }) => {
          this.partmentsList = data || [];
          this.firstParmas.total = page.total;
          this.tableLoading = false;
          this.$nextTick(()=>{
            this.$refs.firstTable.doLayout()
            if(flag) this.getCacheDepartments()
          })
          
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    firstSortChange(column) {
      if (column.order === "descending") {
        this.firstParmas.sort_str = column.prop;
        this.firstParmas.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.firstParmas.sort_str = column.prop;
        this.firstParmas.sort_order = "asc";
      } else {
        this.firstParmas.sort_str = null;
        this.firstParmas.sort_order = null;
      }
      this.getPartmentsList();
    },
    firstcallFather(pageparm) {
      this.firstParmas.page = pageparm.page;
      this.firstParmas.perPage = pageparm.perPage;
      this.getPartmentsList();
    },
  },
};
</script>

<style lang='less'>
.subSearch{
  .el-input__inner{
    height: 32px;
    width: 220px;
  }
}
</style>